# -*- coding: utf-8 -*-
"""
-------------------------------------------------
  @Time : 2024/8/27 
  @Auth : system
  @File : serializers.py
  @IDE  : PyCharm
  @Email: 
  @Company: 
  @Copyright: 
-------------------------------------------------
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import ProductionIssues, Status, IssueImage
from django.conf import settings


class ProductionIssuesModelSerializer(serializers.ModelSerializer):
    # 格式化创建时间和更新时间，确保时间精度
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    # 将status字段改为可读写的CharField，同时保留格式化输出的逻辑
    status = serializers.CharField(required=False, default=Status.PENDING.value)

    def get_status(self, obj):
        # 确保status字段始终作为字符串返回
        # 如果状态为空，返回默认的待解决状态
        if obj.status is None:
            return Status.PENDING.value
        # 强制转换为字符串
        return str(obj.status)

    def to_internal_value(self, data):
        # 处理输入数据，确保status是字符串
        if 'status' in data:
            if data['status'] is None:
                data['status'] = Status.PENDING.value
            else:
                data['status'] = str(data['status'])
        return super().to_internal_value(data)

    def to_representation(self, instance):
        # 重写to_representation方法确保输出时格式化status字段
        ret = super().to_representation(instance)
        ret['status'] = self.get_status(instance)
        return ret

    class Meta:
        model = ProductionIssues
        fields = '__all__'


class IssueImageModelSerializer(serializers.ModelSerializer):
    """生产问题图片序列化器"""
    # 图片URL字段
    image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = IssueImage
        fields = ['id', 'image', 'image_url', 'description', 'create_time', 'update_time']
        # 图片字段只在创建时需要，查看时使用image_url
        read_only_fields = ['image_url', 'create_time', 'update_time']
    
    def get_image_url(self, obj):
        """获取完整的图片URL"""
        if obj.image:
            # 确保URL包含协议和域名
            if obj.image.url.startswith('http'):
                return obj.image.url
            else:
                return f'{settings.BASE_URL}{obj.image.url}'
        return ''


class ProductionIssuesWithImagesModelSerializer(serializers.ModelSerializer):
    """包含图片信息的生产问题序列化器"""
    # 格式化创建时间和更新时间，确保时间精度
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    # 将status字段改为可读写的CharField，同时保留格式化输出的逻辑
    status = serializers.CharField(required=False, default=Status.PENDING.value)
    # 嵌套图片序列化器
    images = IssueImageModelSerializer(many=True, read_only=True)
    
    def get_status(self, obj):
        # 确保status字段始终作为字符串返回
        # 如果状态为空，返回默认的待解决状态
        if obj.status is None:
            return Status.PENDING.value
        # 强制转换为字符串
        return str(obj.status)
    
    def to_internal_value(self, data):
        # 处理输入数据，确保status是字符串
        if 'status' in data:
            if data['status'] is None:
                data['status'] = Status.PENDING.value
            else:
                data['status'] = str(data['status'])
        return super().to_internal_value(data)
    
    def to_representation(self, instance):
        # 重写to_representation方法确保输出时格式化status字段
        ret = super().to_representation(instance)
        ret['status'] = self.get_status(instance)
        return ret
    
    class Meta:
        model = ProductionIssues
        fields = '__all__'


class SearchProductionIssuesModelSerializer(serializers.ModelSerializer):
    # 格式化创建时间和更新时间，确保时间精度
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    # 将status字段改为可读写的CharField，保持与主序列化器一致
    status = serializers.CharField(required=False, default=Status.PENDING.value)

    def get_status(self, obj):
        # 确保status字段始终作为字符串返回
        if obj.status is None:
            return Status.PENDING.value
        return str(obj.status)

    def to_representation(self, instance):
        # 重写to_representation方法确保输出时格式化status字段
        ret = super().to_representation(instance)
        ret['status'] = self.get_status(instance)
        return ret

    class Meta:
        model = ProductionIssues
        fields = '__all__'